//
//  WithdrawCashInfoViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-17.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "WithdrawCashInfoViewController.h"
#import "UserInfoModel.h"
#import "GDataXMLNode.h"
#import "ELifeAppDelegate.h"
#import "GTMBase64.h"
#import "AlertView.h"
#import "GetMyData.h"
#import "UserInfoModel.h"
#import "LoginController.h"

@implementation WithdrawCashInfoViewController

@synthesize cardNumber, phoneNumber, bank, name, bankPosition, password;


UserInfoModel* userInfo;
NSArray* bankNames;
NSArray* bankId;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}



- (void)search
{
    if ([bank.text length] == 0 || [name.text length] == 0 || [bankPosition.text length] == 0)
    {
        [AlertView showAlert:@"请填写完整信息"];
        return;
    }
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
    
    //    请求地址: /user.php 417136
    //    请求参数: action => updatebaseinfo
    //    user_id => 用户id (必填)
    //    以下至少传一项
    //    phone	=> 手机
    //    email	=> 邮件
    //    realname  => 真实姓名
    //    real_id   => 身份证号
    //    bank_name => 提现银行 传拼音 (gongshang=>工商 zhaohang=>招商 jianshe=>建设 nongye=>农行 beijing=>北京 jiaotong=>交通)
    //    bank_num  => 银行卡号
    //    bank_province  => 银行所在省
    //    bank_city  => 银行所在城市 
    //    draw_pw   => 提现密码
    
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"user.php"]];
    
    
    NSString* userName = [GetMyData getUserId];

    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"updatebaseinfo" forKey:@"action"];
    [param setObject:userName forKey:@"user_id"];
    [param setObject:name.text forKey:@"realname"];
    
    
    [param setObject:userInfo.bank_name forKey:@"bank_name"];
    [param setObject:cardNumber.text forKey:@"bank_num"];
    [param setObject:bankPosition.text forKey:@"bank_city"];
    [param setObject:password.text forKey:@"draw_pw"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[[ELifeAppDelegate App] httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [[ELifeAppDelegate App] showProgressDialog:@"请稍候"];
}

- (void)iRequestFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"-----rootElement-----%@\n", rootElement);
    
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"-----headsElement-----%@\n", headsElement);
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
        [alert setTag:11];
        [alert release];
    } else if (code == -124){
        [AlertView showAlert:@"请填写真实姓名"];
    } else if (code == -126){
        [AlertView showAlert:@"请选择银行"];
    } else if (code != 0){
        [AlertView showAlert:@"修改失败"];
    } else {
        [AlertView showAlert:@"修改成功"];
    }
    
    [doc release];
    
}

- (void)dealloc
{
    [super dealloc];
    
    [cardNumber release];
    [phoneNumber release];
    [bank release];
    [name release];
    [bankPosition release];
    [password release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

-(void)initTextFields:(UITextField *)textField
{    
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = (textField == phoneNumber 
                              || textField == cardNumber)
    ? UIKeyboardTypeNumberPad : UIKeyboardTypeDefault;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    bankNames = [[NSArray alloc] initWithObjects:@"工商银行", @"招商银行", @"建设银行", @"农业银行", @"北京银行", @"交通银行", nil];
    bankId = [[NSArray alloc] initWithObjects:@"gongshang", @"zhaohang", @"jianshe", @"nongye", @"beijing", @"jiaotong", nil];
    
    [self initTextFields:phoneNumber];
    [self initTextFields:cardNumber];
    [self initTextFields:bank];
    [self initTextFields:name];
    [self initTextFields:bankPosition];
    [self initTextFields:password];
        
    [self.navigationItem setTitle:@"提现资料"]; 
    
    int index = [bankId indexOfObject:userInfo.bank_name];
    
    userInfo = [UserInfoModel getInstance];
    [phoneNumber setText:userInfo.phone];
    [name setText:userInfo.realname];
    [password setText:userInfo.draw_pw];
    [cardNumber setText:userInfo.bank_num];
    if (index >= 0 && index < [bankNames count]){
        [bank setText:[bankNames objectAtIndex:index]];
    }
    [bankPosition setText:userInfo.bank_city];
    
}
 
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(IBAction)confirm:(id)sender
{
//    [self.navigationController popViewControllerAnimated:YES];
    [self search];
}

-(IBAction)cancel:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	// the user pressed the "Done" button, so dismiss the keyboard
	[textField resignFirstResponder];
	return YES;
}

-(IBAction)choseBank:(id)sender
{
    
	UIActionSheet *styleAlert = [[UIActionSheet alloc] initWithTitle:@"提现银行:"
                                            delegate:self cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                            otherButtonTitles:@"工商银行", @"招商银行", @"建设银行", @"农业银行", @"北京银行", @"交通银行", nil];
	
	// use the same style as the nav bar
	styleAlert.actionSheetStyle = self.navigationController.navigationBar.barStyle;
	
	[styleAlert showInView:self.view];
	[styleAlert release];
    
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex >= [bankNames count])
    {
        return;
    }
    // Change the navigation bar style, also make the status bar match with it
	userInfo.bank_name = [bankId objectAtIndex:buttonIndex];
    [bank setText:[bankNames objectAtIndex:buttonIndex]];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1){
            LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
            
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
        return; 
        
    }
}

- (IBAction)closeKeypad:(id)sender
{
    [name resignFirstResponder];
    [bank resignFirstResponder];
    [cardNumber resignFirstResponder];
    [phoneNumber resignFirstResponder];
    [bankPosition resignFirstResponder];
    [password resignFirstResponder];
    
    [sender resignFirstResponder];
}

@end
